package com.njcb.ams.web.controller;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.njcb.ams.application.BusinessWrokflowManager;
import com.njcb.ams.pojo.dto.standard.EntityResponse;
import com.njcb.ams.pojo.dto.standard.Response;
import com.njcb.ams.pojo.vo.ProcessDefinitionVO;
import com.njcb.ams.support.exception.ExceptionUtil;
import com.njcb.ams.util.AmsAssert;
import com.njcb.ams.util.AmsUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 流程定义
 * 
 * @author liuyanlong
 *
 */
@RestController
@RequestMapping("/workflow/process")
@Api(value = "workflow", tags = "workflow")
public class ProcessDefinitionController {
	@Autowired
	private BusinessWrokflowManager businessworkManager;

	@ApiOperation(value = "已部署流程查询")
	@RequestMapping(value = "definition/query", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> processDefinitionQuery(@RequestBody ProcessDefinitionVO inBean) throws Exception {
		ProcessDefinition queryBean = transProcessDefinitionBean(inBean);
		List<ProcessDefinition> list = businessworkManager.taskInfoPendingQuery(queryBean);
		List<ProcessDefinitionVO> volist = new ArrayList<ProcessDefinitionVO>();
		for (ProcessDefinition processDefinition : list) {
			ProcessDefinitionVO pvo = new ProcessDefinitionVO();
			pvo.setId(processDefinition.getId());
			pvo.setDeploymentId(processDefinition.getDeploymentId());
			pvo.setName(processDefinition.getName());
			pvo.setKey(processDefinition.getKey());
			pvo.setVersion(processDefinition.getVersion());
			pvo.setResourceName(processDefinition.getResourceName());
			volist.add(pvo);
		}
		Map<String, Object> modelMap = new HashMap<String, Object>();
		modelMap.put("success", true);
		modelMap.put("total", volist.size());
		modelMap.put("rows", volist);
		return modelMap;
	}

	@ApiOperation(value = "已部署流程删除")
	@RequestMapping(value = "{deploymentId}", method = RequestMethod.DELETE)
	@ResponseBody
	public Response processDefinitionDelete(@PathVariable("deploymentId") String deploymentId) throws Exception {
		ProcessDefinitionEntity queryBean = new ProcessDefinitionEntity();
		queryBean.setDeploymentId(deploymentId);
		try {
			businessworkManager.taskInfoPendingDelete(queryBean);
		} catch (Exception e) {
			if (e instanceof SQLIntegrityConstraintViolationException){
				ExceptionUtil.throwAppException("存在运行中的流程");
			}else if(null != e.getCause() && e.getCause() instanceof SQLIntegrityConstraintViolationException){
				ExceptionUtil.throwAppException("存在运行中的流程");
			}
		}
		
		return Response.buildSucc();
	}

	private ProcessDefinition transProcessDefinitionBean(ProcessDefinitionVO inBean) {
		ProcessDefinitionEntity queryBean = new ProcessDefinitionEntity();
		if(null == inBean){
			return queryBean;
		}
		if(null != inBean.getId()){
			queryBean.setId(inBean.getId());
		}
		if(null != inBean.getKey()){
			queryBean.setKey(inBean.getKey());
		}
		if(null != inBean.getName()){
			queryBean.setName(inBean.getName());
		}
		if(null != inBean.getVersion()){
			queryBean.setVersion(inBean.getVersion());
		}
		return queryBean;
	}


	@ApiOperation(value = "流程启动", notes = "流程启动")
	@RequestMapping(value = "start", method = RequestMethod.POST)
	@ResponseBody
	public Response startProcessInstance(HttpServletRequest request) throws Exception {
		Map<String, String[]> params = request.getParameterMap();
		HashMap<String, Object> param = new HashMap<String, Object>();
		for (Map.Entry<String, Object> element : param.entrySet()) {
			System.out.println(element.getKey() + "|" + element.getValue());
		}
		String processkey = params.get("procdef")[0];
		String tasknodeid = "start";
		Set<String> paramkeys = params.keySet();
		for (String aa : paramkeys) {
			if (AmsUtils.isNotNull(params.get(aa)[0])) {
				param.put(aa, params.get(aa)[0]);
			}
		}
		param.put(tasknodeid, tasknodeid);
		String businessKey = "";
		if (AmsUtils.isNotNull(param.get("businessKey"))) {
			businessKey = String.valueOf(param.get("businessKey"));
		}
		businessworkManager.workFlowStart(processkey, businessKey, param);
		return Response.buildSucc();
	}

	/**
	 * 显示流程图
	 * 
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "处理流程图", notes = "处理流程任务")
	@RequestMapping(value = "display", method = RequestMethod.POST)
	@ResponseBody
	public EntityResponse<String> display(@RequestBody HashMap<String, String> map) throws Exception {
		AmsAssert.notNull(map.get("id"), "流程不能为空");
		String param = businessworkManager.displayProcessDiagram(map.get("id"));
		//去除字符串首尾引号
		param = param.substring(1, param.length() -1);
		return EntityResponse.build(param);
	}

}
